import urllib

from bs4 import BeautifulSoup
import requests
import xlwt


class Gitee:
    def __init__(self):
        self.page_no = 1
        self.results = []

    def do_request(self):
        try:
            url = f"https://search.gitee.com/?skin=rec&type=repository&q={self.key}&lang={self.lang}&pageno={self.page_no}"
            headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36'
            }
            # 发送请求并获取响应
            response = requests.get(url, headers=headers)
            print(f"正在获取第 {self.page_no} 页的数据")
            soup = BeautifulSoup(response.content, 'html.parser')
            self.parse_content(soup)
            all_a = soup.findAll('a')
            for a in all_a:
                try:
                    if f"?skin=rec&type=repository&q={urllib.parse.quote(self.key)}&lang={urllib.parse.quote(self.lang)}&pageno=" in \
                            a['href']:
                        if "下一页" in a.text and self.page_no <= 20:
                            self.page_no += 1
                            self.do_request()
                except Exception as e:
                    pass
        except Exception as e:
            print(str(e))

    def parse_content(self, soup):
        resps = soup.findAll('a', class_="ns")
        for res in resps:
            self.results.append(res['href'])

    def main(self):
        try:
            self.key = input('请输入搜索关键字')
            self.lang = input('请输入开发语言')
            self.do_request()
            print(f"一共有{len(self.results)}个仓库")
            for item in self.results:
                print(item)
            input('按任意键退出')
        except Exception as e:
            pass

if __name__ == '__main__':
    ai = Gitee()
    ai.main()
